package com.springsecurity.demo.filter;


import com.springsecurity.demo.config.JWTLogoutCache;
import com.springsecurity.demo.model.entity.LoginUser;
import com.springsecurity.demo.model.entity.Users;
import com.springsecurity.demo.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

//    @Autowired
//    private RedisCache redisCache;
    @Autowired
    private JWTLogoutCache jwtLogoutCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            //token不存在，放行
            filterChain.doFilter(request, response);
            return;
        }
        //检查 token 是否在注销缓存中，如果true则该token已被注销
        if (jwtLogoutCache.contains(token)) {
//            throw new RuntimeException("token非法");
//            response.sendError(403, "the token is expiry, please login");
//            return;
            // 返回JSON响应而不是抛出异常
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpServletResponse.SC_FORBIDDEN); // 设置状态码为403
            JSONObject jsonResponse = new JSONObject();
            jsonResponse.put("code", 403);
            jsonResponse.put("message", "the token is expiry");
            jsonResponse.put("data", false);
            response.getWriter().write(jsonResponse.toString());
            return;
        }
        //解析token, 校验token是否合法, 如合法则将token中的用户信息保存到SecurityContext
//        String userid;
        String userInfo;
        LoginUser loginUser;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userInfo = claims.getSubject();
            JSONObject userInfoObject = new JSONObject(userInfo);
            JSONArray authorities = userInfoObject.getJSONArray("authorities");
            List<String> permissions = new ArrayList<>();
            for (int i = 0; i < authorities.length(); i++) {
                permissions.add(authorities.getString(i));
            }
            loginUser = new LoginUser(userInfoObject.getString("username"),
                    userInfoObject.getString("password"), permissions);
        } catch (Exception e) {
//            e.printStackTrace();
            throw new RuntimeException("token非法");
//            response.setContentType("application/json;charset=UTF-8");
//            response.setStatus(HttpServletResponse.SC_FORBIDDEN); // 设置状态码为403
//            JSONObject jsonResponse = new JSONObject();
//            jsonResponse.put("code", 403);
//            jsonResponse.put("message", "the token is invalid");
//            jsonResponse.put("data", false);
//            response.getWriter().write(jsonResponse.toString());
//            return;
        }
        //从redis中获取用户信息
//        String redisKey = "login:" + userid;
//        LoginUser loginUser = redisCache.getCacheObject(redisKey);
//        if(Objects.isNull(loginUser)){
//            throw new RuntimeException("用户未登录");
//        }
        //存入SecurityContextHolder
        //TODO 获取权限信息封装到Authentication中

        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
//        authenticationToken.setAuthenticated(true); //标记为已认证
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }
}

